//
//  PersonInfoVC.m
//  PlayCatchGame
//
//  Created by 流言 on 2018/2/7.
//  Copyright © 2018年 清正. All rights reserved.
//

#import "PersonInfoVC.h"
#import "PersonInfoCell.h"
#import "ZLPhotoManager.h"
#import "XLPhotoBrowser.h"
#import "PersonNameView.h"

@interface PersonInfoVC () <UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate, XLPhotoBrowserDelegate> {
    
    NSString *usrName;
    NSString *headImg;
    
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *dataArray;

@property (strong, nonatomic) UIImage *selectImage;
@property (copy, nonatomic) NSString *name;

@end

@implementation PersonInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArray =@[@"头像", @"昵称"].mutableCopy;
    headImg = [TheGlobalMethod getUserDefault:@"headImg"];
    usrName = [TheGlobalMethod getUserDefault:@"userName"];
    self.name = usrName;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [[SDWebImageManager sharedManager].imageDownloader downloadImageWithURL:[NSURL URLWithString:headImg] options:(SDWebImageDownloaderProgressiveDownload) progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            
        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
            self.selectImage = image;
            [self.tableView reloadData];
        }];
    
        
    });
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (indexPath.section ==0) {
        return 80;
    } else {
        return 44;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 10)];
    headerView.backgroundColor =tableView.backgroundColor;
    return headerView;
}

- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 0.1)];
    footerView.backgroundColor =tableView.backgroundColor;
    return footerView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PersonInfoCell *cell =[tableView dequeueReusableCellWithIdentifier:@"PersonInfoCell"];
    if (!cell) {
        cell =[PersonInfoCell findCellWithIdentifier:@"PersonInfoCell"];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
    }
    cell.indexPath =indexPath;
    cell.nameLabel.text =self.dataArray[indexPath.section];
    if (indexPath.section ==0 && indexPath.row ==0) {
        [cell.rightButton sd_setImageWithURL:[NSURL URLWithString:headImg] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"touxiang"]];
        if (self.selectImage) {
            [cell.rightButton setImage:_selectImage forState:UIControlStateNormal];
        }
    } else {
        if (!isStringEmpty(self.name)) {
            [cell.rightButton setTitle:stringEmpty(self.name) forState:UIControlStateNormal];
        }
    }
    [cell didButtonClickBlock:^(UIButton *button, NSIndexPath *indexPath) {
        if (indexPath.section==0 && indexPath.row ==0) {
            [SRActionSheet sr_showActionSheetViewWithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"查看大图", @"从相册选择", @"拍照"] selectSheetBlock:^(SRActionSheet *actionSheetView, NSInteger index) {
                [self selectSheetIndex:index];
            }];
        } else {
            NSLog(@"修改姓名");
            AlertBgView *alertView =[[AlertBgView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) clickRemove:NO bgColor:[UIColor colorWithWhite:0 alpha:0.6]];
            [alertView showView];
            if (IS_IPHONE_5) {
                alertView.centerView_center.constant =-70;
            } else if (IS_IPHONE_6PLUS) {
                alertView.centerView_center.constant =0;
            } else {
                alertView.centerView_center.constant =-50;
            }
            alertView.centerView_height.constant =190;
            
            CGFloat width =300;
            PersonNameView *nameView =[PersonNameView loadNib:@"PersonNameView" frame:CGRectMake((KScreenWidth-width)/2.0, 0, width, alertView.centerView_height.constant)];
            nameView.nameTF.text =self.name;
            [alertView.centerView addSubview:nameView];
            
            [nameView didButtonClick:^(UIButton *button) {
                if (button ==nameView.cancelButton) {
                    [nameView removeFromSuperview];
                    [alertView removeFromSuperview];
                } else if (button ==nameView.reviseButton) {
                    if (isStringEmpty(nameView.nameTF.text)) {
                        [AppToast showFileWithString:@"请输入昵称" view:nameView];
                    } else if ([nameView.nameTF.text isEqualToString:self.name]) {
                        [nameView removeFromSuperview];
                        [alertView removeFromSuperview];
                    } else {
                        self.name =nameView.nameTF.text;
                        [self _modifyName];
                        [self.tableView reloadData];
                        [nameView removeFromSuperview];
                        [alertView removeFromSuperview];
                    }
                }
            }];
        }
    }];
    return cell;
}
/// 处理 查看大图/从相册选择/拍照
- (void)selectSheetIndex:(NSInteger)index {
    if (index ==0) {
        if (self.selectImage) {
            XLPhotoBrowser *browser = [XLPhotoBrowser showPhotoBrowserWithImages:@[self.selectImage] currentImageIndex:0];
            browser.browserStyle = XLPhotoBrowserStylePageControl;
            [browser setActionSheetWithTitle:@"操作" delegate:self cancelButtonTitle:@"取消" deleteButtonTitle:nil otherButtonTitles:@"保存", nil];
        } else {
            [AppToast showFileWithString:@"您的信息不完整,请上传头像" OffsetY:80];
        }
    } else if (index ==1) {
        [PermissionTool getPhotosPermission:^(NSInteger authStatus) {
            if (authStatus ==1) {
                UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
                imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                imagePicker.allowsEditing = YES;
                imagePicker.delegate = self;
                [[AppToast toast_currentShowTopVC] presentViewController:imagePicker animated:YES completion:nil];
            } else {
                [AppToast showFileWithString:@"您已拒绝访问相册, 请到手机 设置 隐私 中打开权限"];
            }
        }];
    } else if (index ==2) {
        [PermissionTool getCamerasPermission:^(NSInteger authStatus) {
            if (authStatus ==1) {
                if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
                    [AppToast showFileWithString:@"您的设备不支持拍照, 请选择其它资源"];
                    return;
                }
                UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
                imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                imagePicker.allowsEditing = YES;
                imagePicker.delegate = self;
                [[AppToast toast_currentShowTopVC] presentViewController:imagePicker animated:YES completion:nil];
            } else {
                [AppToast showFileWithString:@"您已拒绝访问相机, 请到手机 设置 隐私 中打开权限"];
            }
        }];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}


#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    if (picker.allowsEditing) {
        self.selectImage =[info objectForKey:UIImagePickerControllerEditedImage];
    } else {
        self.selectImage =[info objectForKey:UIImagePickerControllerOriginalImage];
    }
    [HttpUrl upLoadImage:self.selectImage hud:self.view isShow:YES WithSuccessBlock:^(id data) {
        if (BB_isSuccess) {
            NSArray *arr = data[@"data"];
            NSString *imgUrl = [arr firstObject];
            NSInteger usrId = [[[TheGlobalMethod getUserDefault:@"usrid"] description] integerValue];
            [HttpUrl POST:@"user/update" dict:@{@"id":@(usrId),@"headImg":imgUrl} hud:self.view isShow:YES WithSuccessBlock:^(id data) {
                if (BB_isSuccess) {
                    [TheGlobalMethod insertUserDefault:data[@"data"][@"headImg"] Key:@"headImg"];
                } else {
                    ShowAlertTitle(data[@"msg"]);
                }
            }];
        }
    }];
    [self.tableView reloadData];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private Method
- (void)_modifyName {
    NSInteger usrId = [[[TheGlobalMethod getUserDefault:@"usrid"] description] integerValue];

    [HttpUrl POST:@"user/update" dict:@{@"id":@(usrId),@"userName":self.name} hud:self.view isShow:YES WithSuccessBlock:^(id data) {
        if (BB_isSuccess) {
            [TheGlobalMethod insertUserDefault:data[@"data"][@"userName"] Key:@"userName"];
            ShowAlertTitle(@"修改成功");
        } else {
            self.name = [TheGlobalMethod getUserDefault:@"userName"];
            [self.tableView reloadData];
            ShowAlertTitle(@"修改失败");
        }
    }];
    
}

#pragma mark - 长按下载图片
- (void)photoBrowser:(XLPhotoBrowser *)browser clickActionSheetIndex:(NSInteger)actionSheetindex currentImageIndex:(NSInteger)currentImageIndex {
    if (actionSheetindex ==0) {
        [browser saveCurrentShowImage];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
